<?php

namespace app\home\controller;

use app\home\model\Idfa724Model;
use app\home\model\Order;
use app\home\service\NotifyService;
use app\home\service\OrderService;
use think\Db;
use think\Model;
use think\Request;
use think\response\Json;

class Pay800009 extends BasePay{

    const  APPKEY = '4fbf8647367a42c398b42a340679fa4b';
    const  GAMEID = 'classic_arcade_fishery';

    const IS_TEST = 1;

    const MAP = [
        1802068=>'0.99',
        1802069=>'1.99',
        1802070=>'2.99',
        1802071=>'3.99',
        1802072=>'4.99',
        1802073=>'5.99',
        1802074=>'6.99',
        1802075=>'7.99',
        1802076=>'8.99',
        1802077=>'9.99',
        1802078=>'10.99',
        1802079=>'11.99',
        1802080=>'12.99',
        1802081=>'13.99',
        1802082=>'14.99',
        1802083=>'15.99',
        1802084=>'16.99',
        1802085=>'17.99',
        1802086=>'18.99',
        1802087=>'19.99',
        1802088=>'24.99',
        1802089=>'29.99',
        1802090=>'34.99',
        1802091=>'39.99',
        1802092=>'39.99',
        1802093=>'44.99',
        1802094=>'49.99',
        1802095=>'59.99',
        1802096=>'69.99',
        1802097=>'79.99',
        1802098=>'89.99',
        1802099=>'99.99',
        1802100=>'109.99',
        1802101=>'119.99',
        1802102=>'129.99',
        1802103=>'139.99',
        1802104=>'149.99',
        1802105=>'159.99',
        1802106=>'169.99',
        1802107=>'179.99',
        1802108=>'189.99',
        1802109=>'199.99',
        1802110=>'299.99',
    ];

    public function __construct()
    {
        header('Content-Type: text/html;charset=utf-8');
        header('Access-Control-Allow-Origin:*'); // *代表允许任何网址请求
        header('Access-Control-Allow-Methods:POST,GET,OPTIONS,DELETE'); // 允许请求的类型
        header('Access-Control-Allow-Credentials: true'); // 设置是否允许发送 cookies
        header('Access-Control-Allow-Headers: Content-Type,Content-Length,Accept-Encoding,X-Requested-with, Origin'); // 
    }

    public function uinfo(){
        $params = Request::instance()->param();

        if(empty(self::IS_TEST)){
            
            $curl = "https://access-api-test-".$params['countryCode'].".ihago.net";
        }else{
            $curl = "https://access-api-".$params['countryCode'].".ihago.net";
        }
        $param = "/login/jscode2session?appid=".self::GAMEID."&secret=".self::APPKEY."&js_code=".$params['js_code'];
        $response = $this->curl($curl.$param);
        exit($response);
    }


    public function order()
    {
        parent::order();
        $json_string = file_get_contents(env('PLATFORM.USD'));

        $config = json_decode($json_string, true);
        $usd  = $config[$this->order_array['goods_id']];
        if(empty($usd)){
            mylog('计费点对应的美元金额找不到');
            exit(json_encode(['code'=>-1,'msg'=>'','data'=>[]]));
        }
        $item_id = array_flip(self::MAP)[$usd['Mpay']];
        if(empty($item_id)){
            mylog('计费点对应的平台美元金额找不到');
            exit(json_encode(['code'=>-1,'msg'=>'','data'=>[]]));
        }
        $payData = [
            "transaction_id" => $this->order_array['id'],
            "subject" => $this->order_array['goods_name'],
            "item_id" => $item_id,
        ];
        //保存金额和币种
        (new \app\home\model\TradeLog)->where('id', $this->order_array['id'])->update(['dollPrice'=>$usd['Mpay'],'dollPriceType'=>'USD']);
        exit(json_encode(['code'=>200,'msg'=>'success','data'=>$payData]));
    }






    public function notify()
    {
        parent::notify();
        $params = $this->params;
        mylog($params);
        try{
            //验证签名
            $str = $this->signData($params);
            $sign = md5($str.'&key='.self::APPKEY);
            if($sign != strtolower($params['sign'])){
                throw new \Exception('sign false');
            }
            //保存第三方单号
            $tradeLog = (new \app\home\model\TradeLog)->where(['id'=>$params['transaction_game']])->find();
            if (empty($tradeLog)) {
                throw new \Exception('订单不存在');
            }
            $tradeLog->transactionID = $params['transaction_hago'];
            $tradeLog->save();

            $amount = self::MAP[$params['item_id']];
            if(empty($amount)){
                throw new \Exception('计费点对应的平台美元金额找不到');
            }
           
            if ($tradeLog['dollPrice'] != $amount) {
                throw new \Exception('订单金额不一致' . ' 传参:' .  $amount . ' 实际:' . $tradeLog['dollPrice']);
            }
            
            if ($tradeLog["status"] == OrderService::PAY_STATUS_PAID) {
                mylog("800009 订单已经处理过了 订单id".$tradeLog['id']);
                return "success";
            }
            
            //发货
            $notifyService = new NotifyService();
            if($notifyService->notifyProcess($tradeLog) == false){
                throw new \Exception('notifyProcess false');
            }
            return "success";
        }catch (\Exception $exception){
            mylog('800009-error:'.$exception->getMessage().' line:'.$exception->getLine().' file:'.$exception->getFile());
            return 'FAIL';
        }

    }

    public function signData($data)
    {
        ksort($data);
        $tmp = [];
        foreach ($data as $k => $v) {
            if($k == 'sign'){
                continue;
            }
            $tmp[] = $k . '=' . $v;
        }
        $str = implode('&', $tmp);
        return $str;
    }


    
    /**
     * @param $url
     * @param null $body
     * @return bool|string
     * @throws Exception
     */
    protected function curl($url, $body = null)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_URL, $url);
        // curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-type: application/json"));
        curl_setopt($ch, CURLOPT_HTTPHEADER,[]);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS,  $body);
        //TODO 证书
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $response = curl_exec($ch);
        
        curl_close($ch);
        mylog($response);
        return $response;

        
    }
   
}
